package com.htgd.gardenexpo.controller;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.service.GeConTouristProblemFeedbackService;
import com.htgd.gardenexpo.service.GeConTouristProblemService;
import com.htgd.gardenexpo.service.GeConTouristProblemUploadService;
import com.htgd.gardenexpo.utils.GetAmazonS3Client;
import com.htgd.gardenexpo.utils.SecurityParameter;
import com.htgd.gardenexpo.utils.UniteUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author ：hejing
 * @date ：Created in 2021/5/24 17:16
 * @description：常见问题管理
 * @menu: 常见问题管理
 * @modified By：`
 * @version: 1.0
 */
@Api(tags = "常见问题管理")
@RestController
@RequestMapping("/api/commonproblem")
public class CommonProblemController {

    @Value("${upload.absolute.url}")
    public String absolute_url;
    @Value("${local.url}")
    public String local_url;
    @Value("${upload.url}")
    public String upload_url;
    @Value("${spring.file-storage.aws-s3[0].bucket-name}")
    public String bucket_name;


    @Resource
    private GeConTouristProblemService geConTouristProblemService;
    @Resource
    private GeConTouristProblemUploadService geConTouristProblemUploadService;
    @Resource
    private GeConTouristProblemFeedbackService geConTouristProblemFeedbackService;

    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private GetAmazonS3Client getAmazonS3Client;


    /**
     * 新增常见问题
     */
    @PostMapping(value = "/add")
    public CommonResult<JSONObject> add(@RequestBody GeConTouristProblem geConTouristProblem){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            String uploadIds=geConTouristProblem.getUploadIds();
            geConTouristProblemService.insert(geConTouristProblem);
            if (!uploadIds.equals("")){
                for (String uploadId:uploadIds.split(",")){
                    GeConTouristProblemUpload geConTouristProblemUpload =geConTouristProblemUploadService.queryById(Integer.parseInt(uploadId));
                    geConTouristProblemUpload.setProblemId(geConTouristProblem.getProblemId());
                    geConTouristProblemUploadService.update(geConTouristProblemUpload);
                }
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    /**
     * 上传图片
     */
    @PostMapping(value = "/uploadPhoto")
    public String uploadPhoto(@RequestParam(value = "file") MultipartFile file){

        //使用指定的存储平台
        FileInfo fileInfo=fileStorageService.of(file)
                .setPlatform("aws-s3-1")
                .image(img -> img.scale(0.4f))
                .upload();
        return upload_url+fileInfo.getFilename();
    }
    /**
     * 上传文件
     */
    @PostMapping(value = "/uploadFile")
    public GeConTouristProblemUpload uploadFile(@RequestParam(value = "file") MultipartFile file){

        GeConTouristProblemUpload geConTouristProblemUpload = new GeConTouristProblemUpload();
        String fileName = file.getOriginalFilename();  // 文件名
        geConTouristProblemUpload.setFilename(fileName);
        FileInfo fileInfo=fileStorageService.of(file)
                .setPlatform("aws-s3-1")
                .setSaveFilename(System.currentTimeMillis()+"/"+file.getOriginalFilename())
                .upload();
        geConTouristProblemUpload.setFilePath(upload_url+fileInfo.getFilename());
        geConTouristProblemUploadService.insert(geConTouristProblemUpload);
        return geConTouristProblemUpload;
    }

    /**
     * 编辑常见问题
     */
    @PostMapping(value = "/edit")
    public CommonResult<JSONObject> edit(@RequestBody GeConTouristProblem geConTouristProblem){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            String uploadIds=geConTouristProblem.getUploadIds();
            geConTouristProblemService.update(geConTouristProblem);
            if (!uploadIds.equals("")&&uploadIds.contains(",")){
                geConTouristProblemUploadService.deleteByIds(uploadIds.split(","),geConTouristProblem.getProblemId());
                for (String uploadId:uploadIds.split(",")){
                    GeConTouristProblemUpload geConTouristProblemUpload =geConTouristProblemUploadService.queryById(Integer.parseInt(uploadId));
                    geConTouristProblemUpload.setProblemId(geConTouristProblem.getProblemId());
                    geConTouristProblemUploadService.update(geConTouristProblemUpload);
                }
            }else {
                geConTouristProblemUploadService.deleteByProblemId(geConTouristProblem.getProblemId());
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除常见问题
     */
    @PostMapping(value = "/delete")
    public CommonResult<JSONObject> delete(int problem_id){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConTouristProblemService.deleteById(problem_id);
            List<GeConTouristProblemUpload> list=geConTouristProblemUploadService.queryByProblemId(problem_id);
            for (GeConTouristProblemUpload geConTouristProblemUpload:list){
                String path=geConTouristProblemUpload.getFilePath().substring(geConTouristProblemUpload.getFilePath().indexOf(bucket_name+"/"),geConTouristProblemUpload.getFilePath().length()-1);
                getAmazonS3Client.delete(path);
            }
            geConTouristProblemUploadService.deleteByProblemId(problem_id);
            geConTouristProblemFeedbackService.deleteByProblemId(problem_id);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 批量删除常见问题
     */
//    @PostMapping(value = "/deleteAll")
    public CommonResult<JSONObject> deleteAll(String problem_ids){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            if (problem_ids!=null&&!problem_ids.equals("")){
                for (String promo:problem_ids.split(",")){
                    int promoId= Integer.parseInt(promo);
                    delete(promoId);
                }
            }

            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 历史常见问题检索列表
     */
    @GetMapping(value = "/list")
    public CommonResult<List<GeConTouristProblem>> list(PageQuery pageQuery){
        CommonResult<List<GeConTouristProblem>> result = new CommonResult<>();
        try{
            pageQuery.setPageNum((pageQuery.getPageNum()-1)*pageQuery.getPageSize());
            List<GeConTouristProblem> list=geConTouristProblemService.getAllProblemByValue(pageQuery);
            /*if (list != null && list.size() > 1) {
                for (GeConTouristProblem geConTouristProblem : list) {
                    String content= UniteUtils.stripHtml(geConTouristProblem.getProblemContent().toString());
                    if (!content.equals("")){
                        geConTouristProblem.setProblemContent(content.substring(0,content.length()>200?200:content.length()));
                    }else {
                        geConTouristProblem.setProblemContent("");
                    }
                }
            }*/
            pageQuery.setPageSize(0);
            List<GeConTouristProblem> list1=geConTouristProblemService.getAllProblemByValueNoContent(pageQuery);
            result.setCode(200);
            result.setData(list);
            result.setMessage(String.valueOf(list1.size()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 常见问题发布
     */
    @GetMapping(value = "/release")
    public CommonResult<JSONObject> release(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 常见问题取消发布
     */
    @GetMapping(value = "/unpublish")
    public CommonResult<JSONObject> unpublish(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 常见问题排序
     */
    @GetMapping(value = "/sort")
    public CommonResult<List<Map<String,Object>>> sort(){
        CommonResult<List<Map<String, Object>>> result = new CommonResult<>();
        return result;
    }

    /**
     * 常见问题置顶
     */
    @GetMapping(value = "/top")
    public CommonResult<JSONObject> top(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }


    /**
     * 常见问题审核
     */
    @GetMapping(value = "/review")
    public CommonResult<JSONObject> review( GeConTouristProblem geConTouristProblem){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            GeConTouristProblem geConTouristProblem1=geConTouristProblemService.queryById(geConTouristProblem.getProblemId());
            geConTouristProblem1.setStatus(geConTouristProblem.getStatus());
            String feedback=geConTouristProblem.getFeedback();
            geConTouristProblem1.setReleasetime(new Date());
            geConTouristProblemService.update(geConTouristProblem1);
            if (!feedback.equals("")){
                GeConTouristProblemFeedback geConTouristProblemFeedback = new GeConTouristProblemFeedback();
                geConTouristProblemFeedback.setProblemId(geConTouristProblem.getProblemId());
                geConTouristProblemFeedback.setContent(feedback);
                geConTouristProblemFeedbackService.insert(geConTouristProblemFeedback);
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 交通服务审核失败反馈
     */
    @GetMapping(value = "/feedbackInfo")
    public CommonResult<List<GeConTouristProblemFeedback>> feedbackInfo(int trafficId){
        CommonResult<List<GeConTouristProblemFeedback>> result = new CommonResult<>();
        try{
            List<GeConTouristProblemFeedback> list=geConTouristProblemFeedbackService.getinfoByProblemId(trafficId);
            result.setData(list);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    /**
     * 常见问题详情
     */
    @PostMapping(value = "/details")
    @SecurityParameter
    public CommonResult<Map<String,Object>> details(@RequestBody String s){
        CommonResult<Map<String, Object>> result = new CommonResult<>();
        try{
            Integer problemId= JSON.parseObject(s).getInteger("problemId");
            Map<String, Object> map = new HashMap<>();
            GeConTouristProblem geConTouristProblem=geConTouristProblemService.queryById(problemId);
            map.put("problrm",geConTouristProblem);
            List<GeConTouristProblemUpload> geConTouristProblemUploads=geConTouristProblemUploadService.queryByProblemId(problemId);
            map.put("upload",geConTouristProblemUploads);
            PageQuery pageQuery = new PageQuery();
             pageQuery.setReviewStatus("3");
            pageQuery.setPageSize(0);
            List<GeConTouristProblem> nlist=geConTouristProblemService.getAllProblemByValueNoContent(pageQuery);
            List<GeConTouristProblem> list = new ArrayList<>();
            for (int i=0;i<nlist.size();i++){
                GeConTouristProblem geConTouristProblem1=nlist.get(i);
                if (problemId==geConTouristProblem1.getProblemId()){
                    if (nlist.size() >= 3) {
                        if (i < nlist.size() - 3) {
                            if (i != 0) {
                                map.put("up", Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            list.add(Conversion(nlist.get(i + 2)));
                            list.add(Conversion(nlist.get(i + 3)));
                            map.put("more", list);
                        } else if (i == nlist.size() - 3) {
                            if (i != 0) {
                                map.put("up",Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            list.add(Conversion(nlist.get(i + 2)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(0)));
                            }
                            map.put("more", list);
                        } else if (i == nlist.size() - 2) {
                            if (i != 0) {
                                map.put("up", Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(0)));
                                list.add(Conversion(nlist.get(1)));
                            }
                            map.put("more", list);
                        } else if (i == nlist.size() - 1) {
                            if (i != 0) {
                                map.put("up",Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", "");
                            list.add(Conversion(nlist.get(0)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(1)));
                            }
                            map.put("more", list);
                        }
                    } else {
                        if (i == 0 && nlist.size() > 1) {
                            map.put("up", "");
                            map.put("down", Conversion(nlist.get(i + 1)));
                        } else if (i == 0 && nlist.size() == 1) {
                            map.put("up", "");
                            map.put("down", "");
                        } else {
                            map.put("up", Conversion(nlist.get(i - 1)));
                            map.put("down", "");
                        }
                        map.put("more", "");
                    }
                    break;
                }
            }
            result.setData(map);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }
    public GeConTouristProblem  Conversion(GeConTouristProblem geConTouristProblem){
        GeConTouristProblem geConTouristProblem1=geConTouristProblemService.queryById(geConTouristProblem.getProblemId());
        String content=UniteUtils.stripHtml(geConTouristProblem1.getProblemContent().toString());
        if (!content.equals("")){
            geConTouristProblem1.setProblemContent(content.substring(0,content.length()>200?200:content.length()));
        }else {
            geConTouristProblem1.setProblemContent("");
        }
        return geConTouristProblem1;
    }
}
